import { Injectable } from '@nestjs/common';
import { UploadFileDto } from "./dto/file.dto"
import path from 'path';
import fs from 'fs-extra';
import { FileStorage } from "./entities/file-storage.entity";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { FileType } from "@/common/enums/file.enum";

@Injectable()
export class FileStorageService {
  constructor(
    @InjectRepository(FileStorage)
    private readonly fileRepository: Repository<FileStorage>,
  ) { }
  private readonly basePath = path.join(process.cwd(), 'storage', 'files');

  async uploadFile(file: Express.Multer.File, uploadDto: UploadFileDto) {
    const { fileType } = uploadDto;
    const fileExt = path.extname(file.originalname);//获取文件扩展名
    const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1E9)}${fileExt}`;//生成唯一文件名
    const typeDir = path.join(this.basePath, fileType);
    const filePath = path.join(typeDir, uniqueName);
    await fs.ensureDir(typeDir);
    await fs.move(file.path, filePath);
    const fileEntity = await this.fileRepository.save({
      originalName: file.originalname,
      fileName: uniqueName,
      filePath: filePath,
      fileType: fileType,
      mimeType: file.mimetype,
      size: file.size,
      metadata: uploadDto.metadata,
    });

    return fileEntity;



    // const strategy = this.getStorageStrategy(uploadDto.fileType);
    // return strategy.store(file, uploadDto.metadata);
  }

  private getStorageStrategy(fileType: FileType) {
    switch (fileType) {
      case FileType.Novel:
        return new NovelStorageStrategy(this.basePath);
      default:
        return new DefaultStorageStrategy(this.basePath);
    }
  }
}

// 存储策略基类
abstract class StorageStrategy {
  constructor(protected basePath: string) { }

  abstract store(file: Express.Multer.File, metadata?: any): Promise<any>;
}

// 小说存储
class NovelStorageStrategy extends StorageStrategy {
  async store(file: Express.Multer.File, metadata?: any) {
    const { bookId } = metadata;
    const dir = path.join(this.basePath, 'novels', bookId.toString());
  }
}

// 默认存储
class DefaultStorageStrategy extends StorageStrategy {
  async store(file: Express.Multer.File, metadata?: any) {
    const dir = path.join(this.basePath, 'other');
    await fs.ensureDir(dir);
  }
}